package com.ruoyi.web.controller.common;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.oss.entity.UploadResult;
import com.ruoyi.oss.enumd.CloudServiceEnumd;
import com.ruoyi.oss.factory.OssFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * @author zhutianyu
 * @date 2021/8/20 17:33
 */
@Slf4j
@RestController
@RequestMapping("oss")
public class AliyunOssController {

  /**
   * 获取签名,前端只传到oss
   *
   * @return
   */
  @GetMapping("getPolicy")
  @PreAuthorize("@ss.hasPermi('oss:get:policy')")
  public AjaxResult<Map<String, String>> getPolicy(@RequestParam String name) {
    return AjaxResult.success(
        OssFactory.instance(CloudServiceEnumd.ALIYUN.getValue()).getPolicy(name));
  }

  /** 上传文件 */
  @PostMapping("upload")
  @PreAuthorize("@ss.hasPermi('oss:post:upload')")
  public AjaxResult<UploadResult> upload(@RequestBody MultipartFile file) {
    UploadResult result = null;
    try {
      result =
          OssFactory.instance(CloudServiceEnumd.ALIYUN.getValue())
              .upload(
                  file.getInputStream(),
                  IdUtil.simpleUUID()
                      .concat(".")
                      .concat(Objects.requireNonNull(file.getOriginalFilename()).split("\\.")[1]),
                  file.getContentType());
    } catch (IOException e) {
      log.error("upload io exception", e);
    }
    return AjaxResult.success(result);
  }
}
